// QQ飞车 首图 详情图 生成
import { imgUrlToAttr } from "../../api/gameConfig/gameDictionary";
import {
  getURLBase64Image,
  loadImages,
  drawImagesAreaBg,
  drawBgBorder,
} from "./getUrlImg";
import { setPageImgArr } from "./common"
// 生成QQ飞车首图
export async function makeTitleImgQQspeed(data, list, attrs,huoquData) {
  console.log("%c Line:12 🥝 huoquData", "color:#b03734", huoquData);
  console.log("%c Line:11 🍬 attrs", "color:#2eafb0", attrs);
  return new Promise(async (resolve, reject) => {
    let allSkinArr = []
    // if(huoquData){
    //   // 有获取的信息 找出所有的车和车皮
    //   if(huoquData.getspeedKnapsack&&huoquData.getspeedKnapsack.carList){
    //     const carList = huoquData.getspeedKnapsack.carList
    //     if(carList.carT3&&carList.carT3.length){
    //       carList.carT3.forEach(r=>{
    //         allSkinArr.push({
    //           imgUrl:r.icon,
    //           kz1:1,
    //           fieldName:r.name
    //         })
    //       })
    //     }
    //     if(carList.carT2&&carList.carT2.length){
    //       carList.carT2.forEach(r=>{
    //         allSkinArr.push({
    //           imgUrl:r.icon,
    //           kz1:2,
    //           fieldName:r.name
    //         })
    //       })
    //     }
    //     if(carList.carT1&&carList.carT1.length){
    //       carList.carT1.forEach(r=>{
    //         allSkinArr.push({
    //           imgUrl:r.icon,
    //           kz1:3,
    //           fieldName:r.name
    //         })
    //       })
    //     }
    //     if(carList.carS&&carList.carS.length){
    //       carList.carS.forEach(r=>{
    //         allSkinArr.push({
    //           imgUrl:r.icon,
    //           kz1:4,
    //           fieldName:r.name
    //         })
    //       })
    //     }
    //     if(carList.carA&&carList.carA.length){
    //       carList.carA.forEach(r=>{
    //         allSkinArr.push({
    //           imgUrl:r.icon,
    //           kz1:5,
    //           fieldName:r.name
    //         })
    //       })
    //     }
    //   }
    // }
    // 取出已选择项
   
    let zizuan = "";
    let sm = "";
    let huangzu = ''
    let S = 0
    list = list.split(",");
    if (!list || list == []) {
      reject("多选不能为空");
    }

    if (list && list.length) {
      attrs.forEach(async (item1) => {
        if (item1.aavName == "f8") {
          // 紫钻
          item1.childAttributes.forEach(async (item2) => {
            if (item2.id == data.f8) {
              zizuan = item2.fieldName;
            }
          });
        }
        if (item1.aavName == "f9") {
          // 皇族
          item1.childAttributes.forEach(async (item2) => {
            if (item2.id == data.f9) {
              huangzu = item2.fieldName;
            }
          });
        }
        if (item1.aavName == "f1") {
          // 实名
          item1.childAttributes.forEach(async (item2) => {
            if (item2.id == data.f1) {
              sm = item2.fieldName;
            }
          });
        }
        if (item1.fieldType == "checkbox" && item1.isEnable === "0") {
          item1.childAttributes.forEach(async (item2) => {
            if (list.indexOf(String(item2.id)) > -1 && item2.imgUrl) {
              allSkinArr.push(item2);
              if(item1.aavName == "f5"){
                S++
              }
            }
          });
        }
      });
    }
    try {
      const mainBg = await getURLBase64Image(
        "https://imgage.maimaihao.com/makeImg/QQspeed/mainbg.png"
      );
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      canvas.width = mainBg.width;
      canvas.height = mainBg.height;
      context.drawImage(mainBg, 0, 0, mainBg.width, mainBg.height);
      context.fillStyle = "#593800";

      // 左侧展示
      context.font = "bold 35px Adobe Ming Std";
      // 编号 区服 紫钻 皇族 魅力值 S车
      context.fillText(`编号：${data.thirdId || "--"}`, 145, 266); //编号
      context.fillText(
        `区服：${data.groupName || "--"}`,
        145,
        390
      ); //区服
     
      context.fillText(`魅力值：${data.f10 ? data.f10  : '--'}`, 145, 514);
      // context.fillText(`${v || "--"}`, 192, 1031); //V等级 760
      context.fillText(`实名：${sm || "--"}`, 145, 636); 
      context.fillText(`S车数量：${S || "--"}`, 145, 760); 
      context.fillText(`紫钻：${zizuan&&zizuan!='Lv0'?zizuan:"--"}`, 145, 886); 
      context.fillText(`皇族：${huangzu&&huangzu!='Lv0'?huangzu:"--"}`, 145, 1012);
      //  加载皮肤图片 886 1012
      context.font = "34px Adobe Ming Std";
      let wuqiImgs = [];
      if (allSkinArr && allSkinArr.length) {
        // 不在七牛云的图片  传给服务端进行上传
        let notQiniu = []
        allSkinArr.forEach(r=>{
          if(!r.imgUrl.includes('imgage.maimaihao.com')){
            notQiniu.push({
              id:r.id,
              imgUrl:r.imgUrl
            })
          }
        })
        if(notQiniu&&notQiniu.length){
         const attrImgList = await imgUrlToAttr(notQiniu)
          if(attrImgList.data&&attrImgList.data.length){
            attrImgList.data.forEach(r2=>{
              allSkinArr.forEach((r,i)=>{
                if(r.id==r2.id){
                  allSkinArr[i].imgUrl = r2.imgUrl
                }
              })
            })
          }
        }

        // 排序 下载图片
        wuqiImgs = await loadImages(allSkinArr, 15);
        console.log("%c Line:109 🍫 wuqiImgs", "color:#4fff4B", wuqiImgs);
      }
      if (wuqiImgs && wuqiImgs.length) {
        // 武器图片
        // 下载皮肤背景图
        let defaultBg = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/QQspeed/skinbg.png"
        );
        // let wuqi1 = await getURLBase64Image(
        //   "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/jin.png"
        // );
        // let wuqi2 = await getURLBase64Image(
        //   "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/yin.png"
        // );
        // let wuqi3 = await getURLBase64Image(
        //   "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/tong.png"
        // );
        // let wuqi4 = await getURLBase64Image(
        //   "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/cheng.png"
        // );
        // let wuqi5 = await getURLBase64Image(
        //   "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/zi.png"
        // );
        // let wuqi6 = await getURLBase64Image(
        //   "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/lv.png"
        // );
        // let wuqi7 = await getURLBase64Image(
        //   "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/lan.png"
        // );
        let opts = {
          startX: 666,
          startY: 215,
          rowNum: 5,
          stepY: 23,
          stepX: 23,
          txtLineHeight: 30,
          imgWidth1: 330,
          imgHeight: 378,
          // bgImgs: [wuqi1,wuqi2,wuqi3,wuqi4,wuqi5,wuqi6,wuqi7],
          txtInside: true,
          defaultSkinbg: defaultBg,
          gameId: 7,
          textColor: '#593800'
        };
        drawImagesAreaBg(context, wuqiImgs, opts);
        // context.drawImage(mainBg, 0, 0, mainBg.width, mainBg.height);
      }
 
       // 绘制结束
       const base64Url = canvas.toDataURL("image/jpeg", 0.8);
       resolve(base64Url);
    } catch (error) {
      reject(error);
    }
  });
}

// // 生成详情图-QQ飞车 多图
export async function makeDetailImgQQspeed(data, skins, attrs) {
  // console.log("%c Line:147 🍯 attrs", "color:#3f7cff", attrs);
  // console.log("%c Line:147 🍢 skins", "color:#2eafb0", skins);
  // console.log("%c Line:147 🥪 data", "color:#2eafb0", data);
  // data = smock.xqData
  // skins = smock.skins
  // attrs = smock.xqAttrs
  return new Promise(async (resolve, reject) => {
    // // 分页数据
    let { opts, imgPageArr } = await setPageImgArr(skins, {
      headHeight: 110,
      skinLineNum:7,
      skinLineHeight:150,
      typeNameHwight:0,
      gameId:67
    })
    // 下载单个背景图
    let defaultSkinbg = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/SanJiaoZhou/wuqidefaultbg.png"
    );

    let wuqi1 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/jin.png"
    );
    let wuqi2 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/yin.png"
    );
    let wuqi3 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/tong.png"
    );
    let wuqi4 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/cheng.png"
    );
    let wuqi5 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/zi.png"
    );
    let wuqi6 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/lv.png"
    );
    let wuqi7 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/lan.png"
    );
      // // 取出所有图片  一维数组
      // const skinsList = []
      // if (skins && skins.length){
      //   skins.forEach(r=>{
      //     if(r.list&&r.list.length){
      //       r.list.forEach(r2=>{
      //         skinsList.push(r2)
      //       })
      //     }
      //   })
      // }
    // 绘制图片
    let imgsArr = [];
    // if (skinsList && skinsList.length) {
    //   const skinImgs = await loadImages(skinsList, skinsList.length);
    //   // console.log("%c Line:203 🥔 skinImgs", "color:#fca650", skinImgs);
    //   let base64Img = await makeDetailImgWwqyOne(
    //     skinImgs,
    //     data,
    //     [star1,star2,star3,star4,star5],
    //     defaultSkinbg
    //   );
    //   imgsArr.push(JSON.stringify(base64Img));
    //   resolve(imgsArr);
    // }
    imgPageArr
    console.log("%c Line:311 🍣 imgPageArr", "color:#ed9ec7", imgPageArr);
    if (imgPageArr && imgPageArr.length) {
      // console.log("%c Line:184 🥪 imgPageArr", "color:#465975", imgPageArr);
      for (let k = 0; k < imgPageArr.length; k++) {
        let base64Img = await makeDetailImgWwqyOne(
          imgPageArr[k],
          data,
          [wuqi1,wuqi2,wuqi3,wuqi4,wuqi5,wuqi6,wuqi7],
          '',
          opts,
        );
        imgsArr.push(JSON.stringify(base64Img));
        if (k == imgPageArr.length - 1) {
          resolve(imgsArr);
        }
      }
    }
  });
}
// 绘制一个 QQ飞车 详情图
async function makeDetailImgWwqyOne(typeArr, data, bgImgs, defaultSkinbg,opts) {
  ////console.log("%c Line:203 🍌 typeArr", "color:#93c0a4", typeArr);
  let juese1 = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/jin2.png"
  );
  let juese2 = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/yin2.png"
  );
  let juese3 = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/tong2.png"
  );
  let juese4 = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/cheng2.png"
  );
  let juese5 = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/zi2.png"
  );
  let juese6 = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/lv2.png"
  );
  let juese7 = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/lan2.png"
  );
  const jueseBgArr = [juese1,juese2,juese3,juese4,juese5,juese6,juese7]
  // 先计算当前页图片的高度
  let lineHeight = opts.skinHeight||150;
  let skinHeight = 0;
  let lineNum = 0;
  let jueseLineNum = 0;
  let skinNum = 0;
  if (typeArr && typeArr.length) {
    for (let i = 0; i < typeArr.length; i++) {
      let typeMap = typeArr[i];
      if(typeMap.typeName=="人物角色"){
        // 角色一行11个 高度
        jueseLineNum = jueseLineNum + Math.ceil(typeMap.skins.length / 11);
        for (let j = 0; j < typeArr[i].skins.length; j++) {
          let url = typeArr[i].skins[j].imgUrl;
          if (url) {
            try {
              skinNum++;
              const temp = await getURLBase64Image(url);
              typeArr[i].skins[j].image = temp;
            } catch (error) {}
          } else {
            typeArr[i].skins.splice(j, 1);
            j--;
          }
        }

      }else{
        lineNum = lineNum + Math.ceil(typeMap.skins.length / 7);
        for (let j = 0; j < typeArr[i].skins.length; j++) {
          let url = typeArr[i].skins[j].imgUrl;
          if (url) {
            try {
              skinNum++;
              const temp = await getURLBase64Image(url);
              typeArr[i].skins[j].image = temp;
            } catch (error) {}
          } else {
            typeArr[i].skins.splice(j, 1);
            j--;
          }
        }
      }
    }
  }
  skinHeight = Math.ceil(lineNum * lineHeight)+Math.ceil(jueseLineNum * 230) + typeArr.length * opts.typeNameHwight + opts.headHeight+20; //所有皮肤 包括分类标题的高度  页尾距离
  // 开始创建画布
  const xStart = 48
  let y = 102; //图的绘制时距离上端的距离
  let x = xStart; //绘制皮肤时的x距离
  // 创建canvas实例
  const canvas = document.createElement("canvas");
  canvas.style.background = "#233D57";
  const context = canvas.getContext("2d");
  canvas.width = 1500;
  canvas.height = Math.ceil(skinHeight);
  context.font = "20px Adobe Ming Std";
  // 下载分类名称背景
  let typeNameBg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/subtitbg.png"
  );
  // 下载主背景
  let mainBgImg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/QiangzhanWangzhe/topbg.png"
  );
  // 下载基础皮肤背景
  let baseBg = defaultSkinbg
  // // 下载右上角装饰
  let hpjyrg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/heping/hpjyrg.png"
  );
  // 开始绘制
  // 绘制整体背景色
  drawBgBorder(context, 0, 0, canvas.width, skinHeight, {
    radius: 0,
    borderWidth: 0,
    startColor: "#191c24",
    centerColor1: "#191c24",
    centerColor2: "#191c24",
    endColor: "#191c24",
    borderColor: "#1a201c",
  });

  // 绘制背景图
  context.drawImage(mainBgImg, 0, 0, canvas.width, 100);
  // // 绘制标题背景
  // context.drawImage(titleBg, 0, 0, canvas.width, 100);
  // // 填充标题文字
  // context.font = "bold 30px Adobe Ming Std";
  // context.fillStyle = "#fff"; // 文字填充颜色
  // // 头部标题 店铺名
  // context.fillText(
  //   `${data.gameName || "--"}`,
  //   canvas.width / 2 - (data.gameName.length * 30) / 2,
  //   50
  // );

  // 绘制主要区域的背景
  drawBgBorder(context, 28, 110, canvas.width - 56, skinHeight - 110, {
    radius: 12,
    borderWidth: 1,
    startColor: "#1f1e46",
    centerColor1: "#1f1e46",
    centerColor2: "#1f1e46",
    endColor: "#1f1e46",
    borderColor: "#aaa",
  });
  // 绘制右上角装饰 hpjyrg
  context.drawImage(hpjyrg, 1482, 110, 5, 68);


  // 开始绘制皮肤
  if (typeArr && typeArr.length) {
    for (let i = 0; i < typeArr.length; i++) {
      let typeMap = typeArr[i];
      typeMap.skins.sort((a,b)=>a.kz1-b.kz1)
      for (let j = 0; j < typeMap.skins.length; j++) {
        let skin = typeMap.skins[j];
        if (j == 0) {
          // 分组开始  先绘制分类标题图片和分类名
          if (i != 0) {
            if(typeArr[i-1]&&typeArr[i-1].typeName=="人物角色"){
              y += 230;
            }else{
              y += lineHeight;
            }
          }
          context.drawImage(typeNameBg, 0, y-86, 335, 228);
          context.font = "28px Adobe Ming Std";
          context.fillStyle = "#ffffff"; // 文字填充颜色
          let name = typeMap.typeName || "其他";
          // let txtWidth = name.length * 28;
          context.fillText(` ${name}`, 30, y + 40);
          y += 75;
          x = xStart;
        }
        if(typeMap.typeName=="人物角色"){
          if (j % 11 == 0 && j != 0) {
            x = xStart;
            y += 230;
          }
      
          // 绘制每张图中的皮肤
          if (skin.image) {
            // 绘制背景图
            if (skin.kz1 && jueseBgArr[skin.kz1-1]) {
              const bg = jueseBgArr[skin.kz1-1];
              // console.log("%c Line:223 🌭 bg", "color:#f5ce50", bg);
              context.drawImage(bg, x, y, 114, 210);
              context.fillStyle = "#fff"; // 文字填充颜色
            }
            // 绘制皮肤图片
            context.drawImage(skin.image, x + 3, y + 5, 100, 160);
            // 皮肤名称
            context.font = "20px Adobe Ming Std";
            let name = skin.fieldName||''
            if(name.length>5){
              name = name.substring(0,5) + '...'
            }
            context.fillText(
              name,
              x+6,
              y + 200
            );
  
            // // 右上角等级
            // if (skin.kz2) {
            //   context.fillStyle = "#333";
            //   context.fillText(skin.kz2 + "级", x + 185 - 60, y + 20);
            // }
            x += 129;
          }
        }else{
          if (j % 7 == 0 && j != 0) {
            x = xStart;
            y += lineHeight;
          }
          // if (j % 7 == 0 ) {
          //   // 绘制一行7个基础图
          //   let rowx = x
          //   for (let l = 0; l < 7; l++){
          //     context.drawImage(baseBg, rowx, y, 190, 130);
          //     rowx += 202;
          //   }
          // }
          // 绘制每张图中的皮肤
          if (skin.image) {
            // 绘制背景图
            if (skin.kz1 && bgImgs[skin.kz1-1]) {
              const bg = bgImgs[skin.kz1-1];
              // console.log("%c Line:223 🌭 bg", "color:#f5ce50", bg);
              context.drawImage(bg, x, y, 190, 130);
              context.fillStyle = "#fff"; // 文字填充颜色
            } else {
              if (defaultSkinbg) {
                context.drawImage(defaultSkinbg, x, y, 190, 130);
                context.fillStyle = "#fff"; // 文字填充颜色
              }
            }
            // 绘制皮肤图片
            context.drawImage(skin.image, x + 10, y + 10, 170, 90);
            // 皮肤名称
            context.font = "20px Adobe Ming Std";
            let name = skin.fieldName||''
            if(name.length>9){
              name = name.substring(0, 9) + '...'
            }
            context.fillText(
              name,
              x+10,
              y + 120
            );
  
            // // 右上角等级
            // if (skin.kz2) {
            //   context.fillStyle = "#333";
            //   context.fillText(skin.kz2 + "级", x + 185 - 60, y + 20);
            // }
            x += 202;
          }
        }



        
      }
    }
  }
  return canvas.toDataURL("image/jpeg", 1);
}